package gateway;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import reactor.retry.Repeat;

/**
 * 自定义实现过滤器
 */
@Slf4j
@Component
public class CustomGatewayFilterFactory extends AbstractGatewayFilterFactory<CustomConfig> implements Ordered {
    /**
     * 构造方法
     * 此处直接指定类型
     */
    public CustomGatewayFilterFactory() {
        super(CustomConfig.class);
    }


    @Override
    public GatewayFilter apply(CustomConfig config) {
        return new GatewayFilter() {
            /**
             *
             * ServerWebExchange HTTP 请求响应的交互契约, 提供了对http请求和响应的访问
             * GatewayFilterChain 过滤器链
             * Mono Reactor 的核心类, 数据流的发布类, Mono 最多只能发布一个事件, 可以把Mono用异步完成任务时, 发出通知
             * chain.filter(exchange) 执行请求
             * Mono.fromRunnable() 创建一个包含 Runnable 的数据流
             */
            @Override
            public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
                // pre类型 执行请求 post类型
                log.info("Pre Filter, config: {}", config); // pre类型代码逻辑
                return chain.filter(exchange).then(Mono.fromRunnable(() -> {
                    log.info("Post Filter"); // post类型代码逻辑
                }));
            }
        };
    }

    /**
     * 设置优先级
     */
    @Override
    public int getOrder() {
        return Ordered.LOWEST_PRECEDENCE;
    }
}
